import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/utils/http_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';

import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_workreportrecord_odoo_api.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_workreportrecord.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:quiver/strings.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import '../../../generated/l10n.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class UdtTbWorkreportrecordQrscanExceptBanJinList extends StatefulWidget {
  UdtTbWorkreportrecordQrscanExceptBanJinList();

  @override
  _UdtTbWorkreportrecordQrscanExceptBanJinListState createState() =>
      _UdtTbWorkreportrecordQrscanExceptBanJinListState();
}

class _UdtTbWorkreportrecordQrscanExceptBanJinListState
    extends State<UdtTbWorkreportrecordQrscanExceptBanJinList> {
  late UdtTbWorkreportrecord udtTbWorkreportrecord = UdtTbWorkreportrecord();

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  //班次
  late List<SelectOptionVO> shiftList = [];
  //报工人员
  late List<SelectOptionVO> reportworkerList = [];
  //工序
  late List<SelectOptionVO> pathList = [];

  Map routeRemarkMap = {};
  Map planQTYMap = {};
  Map processMap ={};
  Map areaMap ={};


  // List orderRuleList = [];

  // List userCodeList = [];

  List<UdtTbWorkreportrecord> dataList = [];
  UdtTbWorkreportrecord workreportrecord = UdtTbWorkreportrecord();

  // Map keyMap = {};

  ValueNotifier<num> total = ValueNotifier<num>(0);

  late var _subscription;

  @override
  void initState() {
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "workreportrecordQrscan")
        .listen(_onEnvent);
    super.initState();
    _loadSelectVO();
  }

  @override
  void dispose() {
    StoreUtil.write("key", "workreportrecord");
    _subscription.cancel();
    super.dispose();
  }

  //处理扫码后的结果
  void _onEnvent(dynamic obj) async {
    obj = obj["scan"];
    if (obj.contains("|")) {
      // 补单
      await _getData(type: 3, barcode: obj.toString());
    } else {
      // ZPZZ5	装配-总装5组	箱体厂 / 装配车间	装配车间总装5班组
      // ZPZZ4	装配-总装4组	箱体厂 / 装配车间	装配车间总装4班组
      // ZPZZ3	装配-总装3组	箱体厂 / 装配车间	装配车间总装3班组
      // ZPZZ2	装配-总装2组	箱体厂 / 装配车间	装配车间总装2班组
      // ZPZZ1	装配-总装1组	箱体厂 / 装配车间	装配车间总装1班组
      // ZPYP 装配-样品 箱体厂 / 装配车间 装配车间样品班组
      // ZPTP 装配-托盘 箱体厂 / 装配车间 装配车间托盘班组
      if(udtTbWorkreportrecord.teamCode == 'ZPZZ'
          || udtTbWorkreportrecord.teamCode == 'ZPYP'
          || udtTbWorkreportrecord.teamCode == 'ZPTP'
      ){
        await _getData(type: 1, barcode: obj.toString());
      }else{
        await _getData(type: 2, barcode: obj.toString());
      }
    }
    await _getDataList();
  }

  _loadSelectVO() async {
    shiftList = [];
    var res = await DynamicDataApi.getModels(model: 'base.shift');
    var starttime;
    var endtime;
    var index = 0;
    if (res.success!) {
      for (var i = 0; i < res.data.length; i++) {
        shiftList.add(SelectOptionVO(
            value: res.data[i]["id"].toString(),
            label: res.data[i]["shiftname"]));
        if (res.data[i]["shiftcode"] == "1001") {
          index = i;
          starttime = DateTime.parse(
              Utils.getDate() + " " + res.data[i]["starttime"] + ":00");
          endtime = DateTime.parse(
              Utils.getDate() + " " + res.data[i]["endtime"] + ":00");
        }
      }
    }
    if (!DateTime.now().isBefore(starttime) &&
        DateTime.now().isBefore(endtime)) {
      udtTbWorkreportrecord.shiftId = res.data[index]["id"].toString();
    } else {
      udtTbWorkreportrecord.shiftId =
          res.data[index == 0 ? 1 : 0]["id"].toString();
    }
    // orderRuleList = (await DynamicDataApi.dictionaryList("orderrule")).data;
    // userCodeList = (await DynamicDataApi.dictionaryList("usercode")).data;
    _loadData();
  }

  _loadData() {
    Map map = StoreUtil.read(Constant.KEY_PRODUCTIONSTATION);
    udtTbWorkreportrecord.stationId = map["stationId"].toString();
    udtTbWorkreportrecord.stationCode = map["stationCode"].toString();
    udtTbWorkreportrecord.stationName = map["stationName"].toString();
    udtTbWorkreportrecord.factoryId = map["factoryId"].toString();
    udtTbWorkreportrecord.factoryName = map["factoryName"].toString();
    udtTbWorkreportrecord.workshopId = map["workshopId"].toString();
    udtTbWorkreportrecord.workshopName = map["workshopName"].toString();
    udtTbWorkreportrecord.teamId = map["teamId"].toString();
    udtTbWorkreportrecord.teamCode = map["teamCode"].toString();
    if(udtTbWorkreportrecord.teamCode == 'PTPFA'
        ||udtTbWorkreportrecord.teamCode == 'PTPFB'
        ||udtTbWorkreportrecord.teamCode == 'PTPFC'){
      udtTbWorkreportrecord.teamCode = 'PT';
    }else if(udtTbWorkreportrecord.teamCode == 'ZPZZ5'
        || udtTbWorkreportrecord.teamCode == 'ZPZZ4'
        || udtTbWorkreportrecord.teamCode == 'ZPZZ3'
        || udtTbWorkreportrecord.teamCode == 'ZPZZ2'
        || udtTbWorkreportrecord.teamCode == 'ZPZZ1'
        || udtTbWorkreportrecord.teamCode == 'ZPTP'
        || udtTbWorkreportrecord.teamCode == 'ZPYP'
    ){
      udtTbWorkreportrecord.teamCode = 'ZPZZ';
    }else if(udtTbWorkreportrecord.teamCode == 'ZPBZ5'
        || udtTbWorkreportrecord.teamCode == 'ZPBZ4'
        || udtTbWorkreportrecord.teamCode == 'ZPBZ3'
        || udtTbWorkreportrecord.teamCode == 'ZPBZ2'
        || udtTbWorkreportrecord.teamCode == 'ZPBZ1'
    ){
      udtTbWorkreportrecord.teamCode = 'ZPBZ';
    }
    // ZPTP 装配-托盘
    // ZPYP 装配-样品
    // 加载装配总装、装配部装、装配物料的所有
    udtTbWorkreportrecord.teamName = map["teamName"].toString();
    udtTbWorkreportrecord.qualifiedquantity = 0;
    udtTbWorkreportrecord.unqualifiedquantity = 0;
    udtTbWorkreportrecord.repairquantity = 0;
    udtTbWorkreportrecord.cutting = 0;
    udtTbWorkreportrecord.replacenumber = 0;
    reportworkerList = StoreUtil.read(Constant.KEY_REPORTWORKERLIST);
    if(reportworkerList.length == 1){
      udtTbWorkreportrecord.reportworkerId = reportworkerList[0].value.toString();
      udtTbWorkreportrecord.reportworkerName = reportworkerList[0].label.toString();
    }
    setState(() {});
  }

  // bool _isOrder(String barcode) {
  //   for (var value in orderRuleList) {
  //     if(barcode.startsWith(value["dictionarycode"])){
  //       return true;
  //     }
  //   }
  //   return false;
  // }
  //
  // bool _isUser(String barcode) {
  //   for (var value in userCodeList) {
  //     if(barcode.startsWith(value["dictionarycode"])){
  //       return true;
  //     }
  //   }
  //   return false;
  // }

  int _getUserIndex(String id) {
    for (var i = 0; i < reportworkerList.length; i++) {
      if (id == reportworkerList[i].value) {
        return i;
      }
    }
    return -1;
  }

  _getTotal() {
    total.value = 0;
    dataList.forEach((element) {
      total.value += element.qualifiedquantity!;
    });
  }

  _getData({int? type, String? barcode}) async {
    // todo type代表不同的对象（1：成品；2：零件；）
    if (isBlank(barcode)) {
      return;
    }
    try {
      if (type == 1) {
        // todo 成品
        planQTYMap = {};
        processMap = {};
        pathList= [];
        routeRemarkMap ={};
        var res = await HttpUtil.get(
            "http://10.1.13.100/mesapi/ztkd/Plan/GetPlanInfo?PlanId=$barcode");
        if (!res.success! || res.data.length == 0) {
          CryUtils.message("$barcode生产单号不存在！");
          return;
        }
        udtTbWorkreportrecord.productionType = res.data[0]["ProductionType"];
        planQTYMap[res.data[0]['ProductSpec']] = res.data[0]['PlanQTY'];
        var res1 = await HttpUtil.get(
            "http://10.1.13.100/mesapi/ztkd/Plan/GetPlanRouteInfo?PlanId=$barcode");
        if (!res1.success! || res1.data.length == 0) {
          CryUtils.message("$barcode生产单号不存在！");
          return;
        }
        for (var element in res1.data[0]["PlanRoutes"]) {
          for(var element1 in element['RouteDatas']){
            if(element1['OperGroup'] == udtTbWorkreportrecord.teamCode){
              var res = await DynamicDataApi.getModels(
                  model: "mrp.routing.workcenter",
                  key: "note",
                  val: element1['OperId']);
              if (res.success!) {
                if(!routeRemarkMap.containsKey(res.data[0]["id"].toString())){
                  pathList.add(SelectOptionVO(
                      label: element1["OperName"],
                      value: res.data[0]["id"].toString()));
                }
                routeRemarkMap[res.data[0]["id"].toString()] = element1["Remark"];
                if(processMap[res.data[0]["id"].toString()] == null){
                  processMap[res.data[0]["id"].toString()] = [];
                }
                processMap[res.data[0]["id"].toString()].add(element['ProductSpec']);
              }
            }
          }
        }
        if (pathList.length == 1) {
          udtTbWorkreportrecord.processId = pathList[0].value.toString();
        }
        // 添加生产单号
        udtTbWorkreportrecord.productionorderno = barcode;
        return;
      }
      if (type == 2) {
        // todo 零件
        planQTYMap = {};
        processMap = {};
        pathList= [];
        routeRemarkMap ={};
        var res = await HttpUtil.get(
            "http://10.1.13.100/mesapi/ztkd/Plan/GetPlanInfo?PlanId=$barcode");
        if (!res.success! || res.data.length == 0) {
          CryUtils.message("$barcode生产单号不存在！");
          return;
        }
        udtTbWorkreportrecord.productionType = res.data[0]["ProductionType"];
        for (var element in res.data[0]["PlanItems"]) {
          if(planQTYMap.containsKey(element["ProductSpec"])){
            planQTYMap[element["ProductSpec"]] += element["PlanQTY"];
          }else{
            planQTYMap[element["ProductSpec"]] = element["PlanQTY"];
          }
        }
        var res1 = await HttpUtil.get(
            "http://10.1.13.100/mesapi/ztkd/Plan/GetPlanRouteInfo?PlanId=$barcode");
        if (!res1.success! || res1.data.length == 0) {
          CryUtils.message("$barcode生产单号不存在！");
          return;
        }
        for (var element in res1.data[0]["PlanRoutes"]) {
          for(var element1 in element['RouteDatas']){
            if(element1['OperGroup'] == udtTbWorkreportrecord.teamCode){
              var res = await DynamicDataApi.getModels(
                  model: "mrp.routing.workcenter",
                  key: "note",
                  val: element1['OperId']);
              if (res.success!) {
                if(!routeRemarkMap.containsKey(res.data[0]["id"].toString())){
                  pathList.add(SelectOptionVO(
                      label: element1["OperName"],
                      value: res.data[0]["id"].toString()));
                }
                routeRemarkMap[res.data[0]["id"].toString()] = element1["Remark"];
                if(processMap[res.data[0]["id"].toString()] == null){
                  processMap[res.data[0]["id"].toString()] = [];
                }
                processMap[res.data[0]["id"].toString()].add(element['ProductSpec']);
              }
            }
          }
        }
        if (pathList.length == 1) {
          udtTbWorkreportrecord.processId = pathList[0].value.toString();
        }
        // 添加生产单号
        udtTbWorkreportrecord.productionorderno = barcode;
        return;
      }
      if(type == 3){
        // 补单
        planQTYMap = {};
        processMap = {};
        pathList= [];
        routeRemarkMap ={};
        List objList = barcode!.split("|");
        var productCode = objList[1];
        var res = await DynamicDataApi.getModels(
            model: 'product.stockorder',
            key: 'stockorderno',
            val: objList[0]
        );
        if (!res.success! || res.data.length == 0) {
          CryUtils.message("$barcode生产单号不存在！");
          return;
        }
        planQTYMap[productCode] = res.data[0]["orderqty"];
        // 用有用的第一个生产单号获得工序即可
        if (pathList.length == 0) {
          var res1 = await DynamicDataApi.getModels(
              model: 'product.stockorderprocess',
              key: 'stockorderno',
              val: objList[0]
          );
          if (!res1.success! || res1.data.length == 0) {
            CryUtils.message("$barcode生产单号不存在！");
            return;
          }
          for(var element in res1.data){
            processMap[element['process_id'][0].toString()] = [productCode];
            pathList.add(SelectOptionVO(label: element['process_id'][1],value: element['process_id'][0].toString()),);
          }
          // if(StoreUtil.hasData(Constant.KEY_PATHLIST)){
          //   StoreUtil.read(Constant.KEY_PATHLIST).forEach((element) {
          //     pathList.add(element);
          //   });
          // }
          if (pathList.length == 1) {
            udtTbWorkreportrecord.processId = pathList[0].value.toString();
          }
        }
      }
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return "";
    }
  }

  _reset() {
    var reportworkerId = udtTbWorkreportrecord.reportworkerId;
    var reportworkerName = udtTbWorkreportrecord.reportworkerName;
    pathList = [];
    dataList = [];
    planQTYMap = {};
    processMap = {};
    routeRemarkMap ={};
    areaMap = {};
    total.value = 0;
    udtTbWorkreportrecord = UdtTbWorkreportrecord();
    udtTbWorkreportrecord.reportworkerId = reportworkerId;
    udtTbWorkreportrecord.reportworkerName = reportworkerName;
    _loadSelectVO();
    // setState(() {});
  }

  _getDataList() async {
    dataList = [];
    areaMap = {};
    if (!isBlank(udtTbWorkreportrecord.processId)) {
      var routeRemark = "";
      if(routeRemarkMap.containsKey(udtTbWorkreportrecord.processId) &&
        !isBlank(routeRemarkMap[udtTbWorkreportrecord.processId])
      ){
        routeRemark = routeRemarkMap[udtTbWorkreportrecord.processId];
      }
      List productList = processMap[udtTbWorkreportrecord.processId];
      ResponseBodyApi res = await DynamicDataApi.getModels(
          model: "product.workreportrecord",
          key: "productionorderno",
          val: udtTbWorkreportrecord.productionorderno,
          key2: "process_id",
          val2: int.parse(udtTbWorkreportrecord.processId!));
      if (res.success!) {
        Map map = {};
        // 整理相同单号的数量
        for (var i = 0; i < res.data.length; i++) {
          var key = res.data[i]["product_id"][0];
          var val = res.data[i]["qualifiedquantity"];
          if (map.containsKey(key)) {
            map[key] += val;
          } else {
            map[key] = val;
          }
        }

        if(udtTbWorkreportrecord.teamCode == 'PT'){
          var res = await HttpUtil.get("http://10.1.13.100/mesapi/ztkd/CommonData/GetMetalParams?PartCodes=$productList");
          if(res.success!){
            for( var i = 0 ; i < res.data.length; i++){
              areaMap[res.data[i]['PartCode']] = res.data[i]['SprayArea'];
            }
          }
        }
        for (var i = 0; i < productList.length; i++) {
          UdtTbWorkreportrecord workreportrecordCopy = udtTbWorkreportrecord.copyWith();
          var productCode = productList[i];
          if(!planQTYMap.containsKey(productCode)){
            break;
          }
          // 生成对应的产品信息
          await StockQuantOdooApi.HWRequest("product_check",productCode);
          ResponseBodyApi res = await DynamicDataApi.getModels(
              model: "product.template", key: 'default_code', val: productCode);
          if(res.success!){
            var product = res.data[0];
            var qualifiedquantity;
            if (map.containsKey(product['id'])) {
              qualifiedquantity =  planQTYMap[productCode] -
                  map[product['id']];
            }else{
              qualifiedquantity =planQTYMap[productCode];
            }
            if (qualifiedquantity <= 0) {
              workreportrecordCopy.qualifiedquantity = 0;
            } else {
              workreportrecordCopy.qualifiedquantity =
                  qualifiedquantity;
            }
            workreportrecordCopy.sprayArea = areaMap[productCode] != null?areaMap[productCode].toString(): null;
            workreportrecordCopy.productId = product['id'].toString();
            workreportrecordCopy.productCode = productCode;
            workreportrecordCopy.productName = product['name'];
            workreportrecordCopy.spec = product['description']!=false?product['description']:'';
            workreportrecordCopy.planQty = workreportrecordCopy.qualifiedquantity;
            workreportrecordCopy.routeRemark = routeRemark;
            dataList.add(workreportrecordCopy);
          }
        }
        _getTotal();
        setState(() {});
      }
    } else {
      CryUtils.message("选择工序（若是没有工序，请联系管理员）");
      setState(() {});
    }
  }

  num _getPlanQTY(List list, String productCode) {
    for (var element in list) {
      if (element["ProductSpec"] == productCode) {
        return element["PlanQTY"];
      }
    }
    return -1;
  }

  _clearProductCode() {
    setState(() {
      udtTbWorkreportrecord.productId = null;
      udtTbWorkreportrecord.productCode = null;
      udtTbWorkreportrecord.productName = null;
      udtTbWorkreportrecord.spec = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    var rows = this.dataList.map((workreportrecord) {
      var result = DataRow(cells: udtTbWorkreportrecord.teamCode=='PT'?[
      DataCell(Text(workreportrecord.productCode.toString())),
          DataCell(Text(workreportrecord.productName.toString())),
          DataCell(Text(workreportrecord.spec.toString())),
          DataCell(Text(workreportrecord.sprayArea.toString())),
          DataCell(CryInputNum(
            width: 80,
            padding: 0,
            contentPadding: 0,
            value: workreportrecord.qualifiedquantity,
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            onSaved: (v) {
              workreportrecord.qualifiedquantity = v;
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // }
          )),
          DataCell(CryInputNum(
            width: 80,
            padding: 0,
            contentPadding: 0,
            value: workreportrecord.unqualifiedquantity,
            onSaved: (v) {
              workreportrecord.unqualifiedquantity = v;
            },
          )),
          DataCell(CryInputNum(
            width: 80,
            padding: 0,
            contentPadding: 0,
            value: workreportrecord.repairquantity,
            onSaved: (v) {
              workreportrecord.repairquantity = v;
            },
          )),
          DataCell(CryInputNum(
            width: 80,
            padding: 0,
            contentPadding: 0,
            value: workreportrecord.cutting,
            onSaved: (v) {
              workreportrecord.cutting = v;
            },
          )),
          DataCell(CryInputNum(
            width: 80,
            padding: 0,
            contentPadding: 0,
            value: workreportrecord.replacenumber,
            onSaved: (v) {
              workreportrecord.replacenumber = v;
            },
          )),
          DataCell(CryInput(
            width: 150,
            padding: 0,
            contentPadding: 0,
            value: workreportrecord.remark,
            onSaved: (v) {
              workreportrecord.remark = v;
            },
          )),
          ]:[
        DataCell(Text(workreportrecord.productCode.toString())),
        DataCell(Text(workreportrecord.productName.toString())),
        DataCell(Text(workreportrecord.spec.toString())),
        DataCell(CryInputNum(
          width: 80,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.qualifiedquantity,
          onChange: (v) {
            formKey.currentState?.save();
            _getTotal();
          },
          onSaved: (v) {
            workreportrecord.qualifiedquantity = v;
          },
          // validator: (v) {
          //   return v!.isEmpty ? S.of(context).required : null;
          // }
        )),
        DataCell(CryInputNum(
          width: 80,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.unqualifiedquantity,
          onSaved: (v) {
            workreportrecord.unqualifiedquantity = v;
          },
        )),
        DataCell(CryInputNum(
          width: 80,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.repairquantity,
          onSaved: (v) {
            workreportrecord.repairquantity = v;
          },
        )),
        DataCell(CryInputNum(
          width: 80,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.cutting,
          onSaved: (v) {
            workreportrecord.cutting = v;
          },
        )),
        DataCell(CryInputNum(
          width: 80,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.replacenumber,
          onSaved: (v) {
            workreportrecord.replacenumber = v;
          },
        )),
        DataCell(CryInput(
          width: 150,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.remark,
          onSaved: (v) {
            workreportrecord.remark = v;
          },
        )),
      ]);
      return result;
    }).toList();
    if (rows.length != 0) {
      rows.add(DataRow(cells: udtTbWorkreportrecord.teamCode=='PT'?[
        DataCell(Text("合计")),
        // DataCell(Text(total.value.toString())),
        DataCell(ValueListenableBuilder<num>(
          valueListenable: total,
          builder: (context, value, child) {
            return Text(value.toString());
          },
        )),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
      ]:[
        DataCell(Text("合计")),
        // DataCell(Text(total.value.toString())),
        DataCell(ValueListenableBuilder<num>(
          valueListenable: total,
          builder: (context, value, child) {
            return Text(value.toString());
          },
        )),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
      ]));
    }
    var table = DataTable(
      columns: udtTbWorkreportrecord.teamCode=='PT'?[
        DataColumn(label: Text('产品图号')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('阴影面积')),
        DataColumn(label: Text("合格数量")),
        DataColumn(label: Text("不合格数量")),
        DataColumn(label: Text("备货数量")),
        DataColumn(label: Text("刀数")),
        DataColumn(label: Text("换模个数")),
        DataColumn(label: Text("备注")),
      ]:[
        DataColumn(label: Text('产品图号')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text("合格数量")),
        DataColumn(label: Text("不合格数量")),
        DataColumn(label: Text("备货数量")),
        DataColumn(label: Text("刀数")),
        DataColumn(label: Text("换模个数")),
        DataColumn(label: Text("备注")),
      ],
      rows: rows,
    );
    var form = Form(
      key: formKey,
      child: Column(
        children: <Widget>[
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: [
                CrySelect(
                  width: 130,
                  label: '班次',
                  value: udtTbWorkreportrecord.shiftId,
                  dataList: shiftList,
                  onSaved: (v) {
                    udtTbWorkreportrecord.shiftId = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
                CrySelect(
                  width: 200,
                  label: '生产工序',
                  dataList: pathList,
                  value: udtTbWorkreportrecord.processId,
                  onChange: (v) async {
                    if (udtTbWorkreportrecord.processId != v) {
                      udtTbWorkreportrecord.processId = v;
                      _getDataList();
                    }
                  },
                  onSaved: (v) {
                    udtTbWorkreportrecord.processId = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
                CryInput(
                  width: 160,
                  label: '设备工位',
                  value: udtTbWorkreportrecord.stationName,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.stationName = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
                CryInput(
                  width: 160,
                  label: '班组',
                  value: udtTbWorkreportrecord.teamName,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.teamName = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
                CryInput(
                  width: 160,
                  label: '生产车间',
                  value: udtTbWorkreportrecord.workshopName,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.workshopName = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
                CryInput(
                  width: 160,
                  label: '生产工厂',
                  value: udtTbWorkreportrecord.factoryName,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.factoryName = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
              ],
            ),
          ),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: [
                // Container(
                //   width: 200,
                //   padding: EdgeInsets.all(20),
                //   child: TextFormField(
                //     style: TextStyle(color: Colors.black),
                //     decoration: InputDecoration(
                //       labelText: '产品图号',
                //       contentPadding: EdgeInsets.symmetric(horizontal: 10),
                //     ),
                //     controller: TextEditingController(
                //         text: udtTbWorkreportrecord.productCode),
                //     onSaved: (v) {
                //       udtTbWorkreportrecord.productCode = v;
                //     },
                //     validator: (v) {
                //       return v!.isEmpty ? S.of(context).required : null;
                //     },
                //   ),
                // ),
                Container(
                  width: 250,
                  padding: EdgeInsets.all(20),
                  child: TextFormField(
                    style: TextStyle(color: Colors.black),
                    decoration: InputDecoration(
                      labelText: '生产单号',
                      contentPadding: EdgeInsets.symmetric(horizontal: 10),
                    ),
                    controller: TextEditingController(text: udtTbWorkreportrecord.productionorderno),
                    validator: (v) {
                      return v!.isEmpty ? S.of(context).required : null;
                    },
                  ),),
                CryInput(
                  width: 160,
                  label: '报工人',
                  value: udtTbWorkreportrecord.reportworkerName,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.reportworkerName = v;
                  },
                  // validator: (v) {
                  //   return v!.isEmpty ? S.of(context).required : null;
                  // },
                ),
                // CryInput(
                //   width: 200,
                //   label: '产品名称',
                //   value: udtTbWorkreportrecord.productName,
                //   enable: false,
                //   onSaved: (v) {
                //     udtTbWorkreportrecord.productName = v;
                //   },
                //   validator: (v) {
                //     return v!.isEmpty ? S.of(context).required : null;
                //   },
                // ),
                // CryInput(
                //   width: 200,
                //   label: '材料型号',
                //   value: udtTbWorkreportrecord.spec,
                //   enable: false,
                //   onSaved: (v) {
                //     udtTbWorkreportrecord.spec = v;
                //   },
                //   // validator: (v) {
                //   //   return v!.isEmpty ? S.of(context).required : null;
                //   // },
                // ),
              ],
            ),
          ),
          SingleChildScrollView(scrollDirection: Axis.horizontal, child: table),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            if (dataList.length == 0) {
              CryUtils.message("请扫描单子");
              return;
            }
            if (isBlank(udtTbWorkreportrecord.reportworkerId)) {
              CryUtils.message("请配置报工人");
              return;
            }
            form.save();
            udtTbWorkreportrecord.status = '0';
            udtTbWorkreportrecord.reportDate =
                DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());
            // List saveData = dataList
            //     .map((e) {
            //       if(e.qualifiedquantity != 0){
            //         e.listToOdooMap(udtTbWorkreportrecord: udtTbWorkreportrecord);
            //       }
            //     }).toList();
            List saveData = [];
            dataList.forEach((element) {
              if (element.qualifiedquantity != 0){
                saveData.add(element.listToExBanjinOdooMap(
                    udtTbWorkreportrecord: udtTbWorkreportrecord));
              }
            });
            UdtTbWorkreportrecordOdooApi.batchSave(saveData)
                .then((ResponseBodyApi res) {
              if (!res.success!) {
                // CryUtils.message(res.message!);
                return;
              }
              // Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
              _reset();
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: "返回",
          onPressed: () {
            Navigator.pop(context, true);
          },
          iconData: Icons.arrow_back,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            return SizedBox.shrink();
          },
        ),
        title: Text("生产报工数据填报"),
        // actions: [ CryButton(
        //   label: "扫码",
        //   onPressed: () {
        //     _scan();
        //   },
        //   iconData: Icons.qr_code_scanner_outlined,
        // ) ] ,
      ),
      body: Column(
        children: [
          Expanded(
              child: SingleChildScrollView(
            child: form,
          )),
          // dataList.length != 0? SingleChildScrollView(
          //   scrollDirection:Axis.horizontal,
          //   child: Row(
          //     children: [
          //       Text("合计"),
          //       CryInputNum(
          //         width: 80,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.qualifiedquantity,
          //         onChange: (val) => _getTotal1(),
          //         onSaved: (v) {
          //           workreportrecord.qualifiedquantity = v;
          //         },
          //         // validator: (v) {
          //         //   return v!.isEmpty ? S.of(context).required : null;
          //         // }
          //       ),
          //       CryInputNum(
          //         width: 80,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.unqualifiedquantity,
          //         onSaved: (v) {
          //           workreportrecord.unqualifiedquantity = v;
          //         },
          //       ),
          //       CryInputNum(
          //         width: 80,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.repairquantity,
          //         onSaved: (v) {
          //           workreportrecord.repairquantity = v;
          //         },
          //       ),
          //       CryInputNum(
          //         width: 80,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.cutting,
          //         onSaved: (v) {
          //           workreportrecord.cutting = v;
          //         },
          //       ),
          //       CryInputNum(
          //         width: 150,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.replacenumber,
          //         onSaved: (v) {
          //           workreportrecord.replacenumber = v;
          //         },
          //       ),
          //       CryInput(
          //         width: 150,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.remark,
          //         onSaved: (v) {
          //           workreportrecord.remark = v;
          //         },
          //       ),
          //     ],
          //   ),
          // ):Container(),
        ],
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      // width: 700,
      height: 700,
      child: result,
    );
    // return result;
  }
}
